app.controller('UserRoleModalCtrl', function ($scope, $modalInstance, toaster, param, ajax) {

	var inserter = new Req.POST({ resource: $scope.resource });

	$scope.submitting = false;
	$scope.param = param;
	if ($scope.param.data == null) {
		$scope.param.data = {};
	}

	$scope.rolelist = $scope.param.role_list;
	$scope.multiSelected = $scope.rolelist;

	$scope.loadRole = function () {
		ajax.call(new Req.GET({
			resource: 'staff/' + param.data.id + '/role'
		})).then(function (result) {
			$scope.stafflist = result.result;
			$scope.multiSelected.rolelist = [];
			for (var idx in $scope.stafflist) {
				for (var j in $scope.rolelist) {
					if ($scope.stafflist[idx].id == $scope.rolelist[j].id) {
						$scope.multiSelected.rolelist.push($scope.rolelist[j]);
						continue;
					}
				}
			}
		}, function () { });
	};
	$scope.loadRole();

	$scope.ids = [];
	$scope.ok = function () {
		for (var i in $scope.multiSelected.rolelist) {
			$scope.ids.push($scope.multiSelected.rolelist[i].id);
		}
		if ($scope.ids != "" && $scope.ids != null && $scope.ids != undefined) {
			inserter.datalist = $scope.ids;
			inserter.resource = 'staff/' + param.data.id + '/role/grant'
			ajax.call(inserter).then(function (result) {
				if (result.code == 200) {
					toaster.pop('success', '成功', '分配角色成功。');
				} else {
					toaster.pop('error', '错误', '分配角色失败！');
				}
			}, function (data) {
				toaster.pop('error', '错误', '分配角色失败！');
			});
			$modalInstance.dismiss('cancel');
		} else {
			toaster.pop('warning', '提示', '请选择角色！');
			$scope.submitting = false;
			return;
		}
	};

	$scope.cancel = function () {
		$modalInstance.dismiss('cancel');
		$scope.submitting = false;
	};
});